package com.blog.controller;

import com.blog.exception.ExceptionEnum;
import com.blog.exception.MyException;
import com.blog.pojo.Article;
import com.blog.pojo.ArticleWithAuthorNameVO;
import com.blog.pojo.PageBean;
import com.blog.pojo.ResultResponse;
import com.blog.service.ArticleService;
import com.blog.utils.AliOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


// 文章管理控制层
@Slf4j
@RequestMapping("/articles")
@RestController
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    // 分页展示所有文章
    @GetMapping
    public ResultResponse listAll(@RequestParam (defaultValue = "1") Integer page) {
        log.info("分页展示所有文章");
        Integer pageSize = 10;
        PageBean pageBean =articleService.listAll(page, pageSize);
        return ResultResponse.success(pageBean);
    }

    // 查看单篇文章
    @GetMapping("/{id}")
    public ResultResponse listById(@PathVariable Integer id) {
        log.info("查询单篇文章，文章id：{}", id);
        ArticleWithAuthorNameVO articleWithAuthorNameVO = articleService.listById(id);
        return ResultResponse.success(articleWithAuthorNameVO);
    }


    // 分页展示一个标签内的所有文章
    @GetMapping("/byTag/{tagId}")
    public ResultResponse listByTag(@PathVariable Integer tagId, @RequestParam (defaultValue = "1") Integer page) {
        log.info("分页查询标签内文章，标签id：{}", tagId);
        Integer pageSize = 10;
        PageBean pageBean = articleService.listByTag(tagId, page, pageSize);
        return ResultResponse.success(pageBean);
    }

    // 分页查看关注文章
    // 根据token, 记得改
    @GetMapping("/byFocus")
    public ResultResponse listByFocus(@RequestParam (defaultValue = "1") Integer page) {
        log.info("分页查看当前用户关注文章");
        Integer pageSize = 10;
        PageBean pageBean = articleService.listByFocus(page, pageSize);
        return ResultResponse.success(pageBean);
    }

    // 分页查看用户文章
    @GetMapping("/byUserId/{id}")
    public ResultResponse listByUserId(@PathVariable Integer id, @RequestParam (defaultValue = "1") Integer page) {
        log.info("分页查看用户文章，用户id：{}", id);
        Integer pageSize = 10;
        PageBean pageBean = articleService.listByUserId(id, page, pageSize);
        return ResultResponse.success(pageBean);
    }

    // 分页查看当前登录用户的所有文章，token，改
    @GetMapping("/currentUser")
    public ResultResponse listCurrentUser(@RequestParam (defaultValue = "1") Integer page) {
        log.info("分页查看当前登录用户的所有文章");
        Integer pageSize = 10;
        PageBean pageBean = articleService.listCurrentUser(page, pageSize);
        return ResultResponse.success(pageBean);
    }

    // 分页查看当前登录用户感兴趣的所有文章，token，改
    @GetMapping("/byHobbies")
    public ResultResponse listByHobbies(@RequestParam (defaultValue = "1") Integer page) {
        log.info("分页查看当前登录用户感兴趣的所有文章");
        Integer pageSize = 10;
        PageBean pageBean = articleService.listByHobbies(page, pageSize);
        return ResultResponse.success(pageBean);
    }

    // 分页查看搜索匹配到的文章
    @GetMapping("/byCondition")
    public ResultResponse listByCondition(@RequestParam String condition, @RequestParam (defaultValue = "1") Integer page) {
        log.info("分页查询搜索字符串匹配的所有文章，字符串：{}", condition);
        if(condition == null) {
            return ResultResponse.error(ExceptionEnum.EMPTY_CONDITION);
        }
        Integer pageSize = 10;
        PageBean pageBean = articleService.listByCondition(condition, page, pageSize);
        return ResultResponse.success(pageBean);
    }

    @Autowired
    private AliOSSUtils aliOSSUtils;

    // 发布文章
    @PostMapping("/create")
    public ResultResponse add(@RequestParam("title") String title,
                      @RequestParam("content") String content,
                      @RequestParam(value = "images", required = false) List<MultipartFile> images,
                      @RequestParam("tagIds") List<Integer> tagIds) throws IOException {
        log.info("发布文章");

        if(title == null) {
            return ResultResponse.error(ExceptionEnum.EMPTY_TITLE);
        }
        if(content == null) {
            return ResultResponse.error(ExceptionEnum.EMPTY_CONTENT);
        }
        if(tagIds == null) {
            return ResultResponse.error(ExceptionEnum.EMPTY_TAG);
        }

        List<String> imageUrls = new ArrayList<>();
        int cnt = 0;
        String coverImage = null;

        if(images != null) {
            for(MultipartFile image : images) {
                if(!image.isEmpty()) {
                    cnt++;
                    String imageUrl = aliOSSUtils.upload(image);
                    if(cnt == 1){
                        coverImage = imageUrl;
                    }
                    imageUrls.add(imageUrl);
                }
            }

            for(String imageUrl : imageUrls) {
                content = content.replaceFirst("src=\"blob:[^\"]*\"", "src=\"" + imageUrl + "\"");
            }
        }

        Article article = new Article();
        article.setContent(content);
        article.setTitle(title);
        article.setSupport(0);
        article.setImage(coverImage);
        articleService.add(article,tagIds);

        return ResultResponse.success();
    }

    // 编辑文章
    @PutMapping("/update/{id}")
    @Transactional(rollbackFor = Exception.class)
    public ResultResponse update(@PathVariable Integer id,
                         @RequestParam("title") String title,
                         @RequestParam("content") String content,
                         @RequestParam(value = "images", required = false) List<MultipartFile> images)throws IOException {
        log.info("编辑文章");

        // 获取原有文章
        Article article = articleService.findById(id);

        log.info("发布文章");

        if(title == null) {
            return ResultResponse.error(ExceptionEnum.EMPTY_TITLE);
        }
        if(content == null) {
            return ResultResponse.error(ExceptionEnum.EMPTY_CONTENT);
        }
        
        // 处理新上传的图片
        List<String> imageUrls = new ArrayList<>();
        Integer cnt=0;
        String coverImage = null;
        if(images != null) {
            for(MultipartFile image : images) {
                if(!image.isEmpty()) {
                    cnt = cnt + 1;
                    String imageUrl = aliOSSUtils.upload(image);
                    if(cnt == 1){
                        coverImage = imageUrl;
                    }
                    imageUrls.add(imageUrl);
                }
            }
            for(String imageUrl : imageUrls) {
                content = content.replaceFirst("src=\"blob:[^\"]*\"", "src=\"" + imageUrl + "\"");
            }
        }

        article.setTitle(title);
        article.setContent(content);
        article.setImage(coverImage);

        articleService.update(article);

        return ResultResponse.success();
    }

    // 批量删除文章
    @DeleteMapping("/delete/{ids}")
    public ResultResponse delete(@PathVariable List<Integer> ids) {
        log.info("批量删除文章，文章id：{}", ids);
        articleService.delete(ids);
        return ResultResponse.success();
    }

    // 给文章点赞
    @PutMapping("/support/{id}")
    public ResultResponse support(@PathVariable Integer id) {
        log.info("给文章点赞，文章id: {}", id);
        if(!articleService.support(id)) {
            throw new MyException(ExceptionEnum.INVALID_SUPPORT);
        }
        return ResultResponse.success();
    }

    // 推荐文章排行榜（按点赞）
    @GetMapping("/sortBySupport")
    public ResultResponse sortBySupport() {
        log.info("文章推荐排行榜，展示前五");
        List<Article> articleList = articleService.sortBySupport(5);
        return ResultResponse.success(articleList);
    }

}
